package repository

import (
	"context"
	"github.com/ecodeclub/ekit/sqlx"
	"jk-time/webook/internal/dao"
	"jk-time/webook/internal/domain"
)

var ErrWaitingSMSNotFound = dao.ErrWaitingSMSNotFound
//go:generate mockgen -source=./retry.go -package=mocks -destination=mocks/retry.mock.go RetryRepository
type RetryRepository interface {
	Create(ctx context.Context, r domain.Retry) error
	PreemptWaitingSMS(ctx context.Context) (domain.Retry, error)
	ReportScheduleResult(ctx context.Context, id int64, res bool) error
}
type CacheRetryRepository struct {
	dao dao.RetryDAO
}

func NewRetryRepository(dao dao.RetryDAO) RetryRepository {
	return &CacheRetryRepository{dao: dao}
}
func (c *CacheRetryRepository) Create(ctx context.Context, r domain.Retry) error {
	return c.dao.Insert(ctx, c.toEntity(r))
}
func (c *CacheRetryRepository) PreemptWaitingSMS(ctx context.Context) (domain.Retry, error) {
	retry, err := c.dao.GetWaitingSMS(ctx)
	return c.toDomain(retry), err
}
func (c *CacheRetryRepository) ReportScheduleResult(ctx context.Context, id int64, res bool) error {
	if res {
		return c.dao.MakeSuccess(ctx, id)
	}
	return c.dao.MakeFail(ctx, id)
}
func (c *CacheRetryRepository) toEntity(r domain.Retry) dao.Retry {
	return dao.Retry{
		Id: r.Id,
		Config: sqlx.JsonColumn[dao.SmsConfig]{
			Val: dao.SmsConfig{
				Args:    r.Args,
				Biz:     r.Biz,
				Numbers: r.Numbers,
			},
		},
		// 重试次数
		RetryCnt: r.RetryCnt,
		// 重试的最大次数
		RetryMax: r.RetryMax,
		Status:   r.Status,
	}
}
func (c *CacheRetryRepository) toDomain(r dao.Retry) domain.Retry {
	return domain.Retry{
		Id:      r.Id,
		Biz:     r.Config.Val.Biz,
		Args:    r.Config.Val.Args,
		Numbers: r.Config.Val.Numbers,
		// 重试次数
		RetryCnt: r.RetryCnt,
		// 重试的最大次数
		RetryMax: r.RetryMax,
		Status:   r.Status,
	}
}
